package com.itliang.mqtt.service;

import com.itliang.manager.AsyncManager;
import com.itliang.manager.factory.AsyncFactory;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

/**
 * @author : liangzhuoyuan
 * @createDate : 2023-03-20 2:51
 */
@Component
@Slf4j
public class MqttCallbackService implements MqttCallback {

    /**
     * 与MQTT服务器连接断开后的回调
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        log.info("[MQTT1] 连接断开，10S之后尝试重连...");
        while (true) {
            try {
                Thread.sleep(1000);
                break;
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 接收所订阅Topic推送的消息
     *
     * @param topic
     * @param mqttMessage
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        String message = new String(mqttMessage.getPayload());
        AsyncManager.me().execute(AsyncFactory.handlerSubscribeMessage(topic, message));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}
